const Ext = chrome || browser

const channels: Record<string, ((message: any, sender: any, sendResponse: any) => void)[] | null> = {}

export const runtimeSendMessage = (channel: string, ...args: any[]) => {
    return Ext.runtime.sendMessage({
        channel,
        ...args
    });
};

export const runtimeOnMessage = (channel: string, listener: (message: any, sender: any, sendResponse: any) => void) => {
    if (channels[channel]) {
        throw new Error(`Channel ${channel} already exists`)
    } else {
        channels[channel] = [listener]
    }
    return Ext.runtime.onMessage.addListener((message, sender, sendResponse) => {
        listener(message, sender, sendResponse)
    });
};

export const runtimeOffMessage = (channel: string, listener: (message: any, sender: any, sendResponse: any) => void) => {
    if (channels[channel]) {
        channels[channel] = null
    }
    return Ext.runtime.onMessage.removeListener(listener);
};

export const isExt = () => {
    return Ext?.runtime
};

export const ExtRuntime = isExt() ? {
    on: runtimeOnMessage,
    off: runtimeOffMessage,
    addListener: runtimeOnMessage,
    removeListener: runtimeOffMessage,
    invoke: runtimeSendMessage,
} : {
    on: () => { },
    off: () => { },
    addListener: () => { },
    removeListener: () => { },
    invoke: () => { },
}



